package com.yupi.usercenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.usercenter.common.ErrorCode;
import com.yupi.usercenter.exception.BusinessExpection;
import com.yupi.usercenter.model.domain.User;
import com.yupi.usercenter.service.UserService;
import com.yupi.usercenter.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.yupi.usercenter.contant.UserConstant.USER_LOGIN_STATE;

/**
* @author hehe
* @description 针对表【user】的数据库操作Service实现
* @createDate 2024-04-12 23:43:10
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{

    @Resource
    UserMapper userMapper;

    /**
     * 盐值 混淆加密
     */
    private static final String SALT = "yupi";


    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword,String plantCode) throws NoSuchAlgorithmException {
        //1.校验
        if(StringUtils.isAnyBlank(userAccount,userPassword,checkPassword,plantCode)){
            //todo改自定义异常处理
            throw new BusinessExpection(ErrorCode.PARAMS_ERROR,"参数为空");
        }
        if(userAccount.length() < 4){
            throw new BusinessExpection(ErrorCode.PARAMS_ERROR,"账户长度小于4");
        }
        if(userPassword.length() < 8 || checkPassword.length() < 8){
            throw new BusinessExpection(ErrorCode.PARAMS_ERROR,"密码长度小于8");
        }
        if(plantCode.length() > 5){
            throw new BusinessExpection(ErrorCode.PARAMS_ERROR,"星球编号大于5");
        }
        if(!userPassword.equals(checkPassword)){
            throw new BusinessExpection(ErrorCode.PARAMS_ERROR,"两次密码不一致");
        }
        //2.校验账户包含特殊字符
        String validRule = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%…… &*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validRule).matcher(userAccount);
        // 如果包含非法字符，则返回
        if(matcher.find()){
            throw new BusinessExpection(ErrorCode.PARAMS_ERROR,"账户包含非法字符串");
        }


        //4.账户不能重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount",userAccount);
        long count = userMapper.selectCount(queryWrapper);
        if(count > 0){
            throw new BusinessExpection(ErrorCode.NULL_ERROR,"账户重复");
        }


        //5,星球编号不能重复
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("plantCode",plantCode);
        count = userMapper.selectCount(queryWrapper);
        if(count > 0){
            throw new BusinessExpection(ErrorCode.NULL_ERROR,"星球编号重复");
        }

        //对密码进行加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        //插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setPlantCode(plantCode);
        boolean saveResult = this.save(user);
        if(!saveResult){
            throw new BusinessExpection(ErrorCode.NULL_ERROR,"注册失败");
        }
        return user.getId();//返回的是Long类型 如果返回值为null 会报错
    }



    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        if(StringUtils.isAnyBlank(userAccount,userPassword)){
            throw new BusinessExpection(ErrorCode.PARAMS_ERROR,"账号密码不能为空");
        }
        if(userAccount.length() < 4){
            throw new BusinessExpection(ErrorCode.PARAMS_ERROR,"账户长度小于4");
        }
        if(userPassword.length() < 8){
            throw new BusinessExpection(ErrorCode.PARAMS_ERROR,"密码长度小于8");
        }
        //2.校验账户包含特殊字符
        String validRule = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%…… &*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validRule).matcher(userAccount);
        // 如果包含非法字符，则返回
        if(matcher.find()){
            throw new BusinessExpection(ErrorCode.PARAMS_ERROR,"包含非法字符");
        }
        //3.对密码进行加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount",userAccount);
        queryWrapper.eq("userPassword",encryptPassword);
        User user = userMapper.selectOne(queryWrapper);
        System.out.println(user);
        if(user == null){
            log.info("登录失败，用户不存在或密码错误");
            throw new BusinessExpection(ErrorCode.PARAMS_ERROR,"账户或者用户不存在");
        }

        //用户脱敏
        User safetyUser = getSafetyUser(user);
        //记录的用户登录态
        request.getSession().setAttribute(USER_LOGIN_STATE,safetyUser);
        return safetyUser;
    }

    /**
     * 逻辑删除
     * @param id
     * @return
     */
    @Override
    public boolean deleteUser(long id) {
        if(id <= 0){
            throw new BusinessExpection(ErrorCode.PARAMS_ERROR,"id错误");
        }
        int i = userMapper.deleteById(id);
        if(i >0){
            return true;
        }
        throw new BusinessExpection(ErrorCode.NULL_ERROR,"删除失败");
    }

    @Override
    public int userLogout(HttpServletRequest request) {
        //移除登录态
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return 1;
    }

    /**
     * 用户脱敏
     * @param user
     * @return
     */
    @Override
    public User getSafetyUser(User user){
        if(user == null) return null;
        //用户脱敏
        User safetyUser = new User();
        safetyUser.setId(user.getId());
        safetyUser.setUsername(user.getUsername());
        safetyUser.setUserAccount(user.getUserAccount());
        safetyUser.setAvatarUrl(user.getAvatarUrl());
        safetyUser.setGender(user.getGender());
        safetyUser.setPhone(user.getPhone());
        safetyUser.setEmail(user.getEmail());
        safetyUser.setPlantCode(user.getPlantCode());
        safetyUser.setUserStatus(user.getUserStatus());
        safetyUser.setCreateTime(user.getCreateTime());
        safetyUser.setUserRole(user.getUserRole());

        return safetyUser;
    }


}




